#include "echo.h"

// ================================================================================

#define BUF_LEN 1024

int main(int argc, char *argv[]) {
  int svr_sock;
  int reuseaddr_val;
  sockaddr_in_t svr_host;
  char buf[BUF_LEN];

  svr_sock = socket(AF_INET, SOCK_STREAM, 0);
  if (svr_sock == -1) {
    perror("Failed to create a network socket");
    return 1;
  }

  reuseaddr_val = 1;
  setsockopt(svr_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_val, sizeof(int));

  svr_host.sin_family = AF_INET;
  svr_host.sin_port = htons(ECHO_PORT);
  svr_host.sin_addr.s_addr = INADDR_ANY;

  if (bind(svr_sock, (sockaddr_t*)&svr_host, sizeof(svr_host)) == -1) {
    perror("Failed to bind to the network socket");
    close(svr_sock);
    return 1;
  }

  listen(svr_sock, 5);

  int client;
  while ((client = accept(svr_sock, NULL, NULL)) != -1) {
    int len = recv(client, buf, BUF_LEN, 0);

    if (len > 0) {
      send(client, buf, len, 0);
    } else {
      perror("Failed to receive from a client");
    }

    close(client);    
  }

  close(svr_sock);

  return 0;
}
